package com.xiaozhi.xzadmin.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.wf.captcha.utils.CaptchaUtil;
import com.xiaozhi.xzadmin.config.Aop.AopLogger;
import com.xiaozhi.xzadmin.pojo.AjaxResult;
import com.xiaozhi.xzadmin.pojo.CommonUtil;
import com.xiaozhi.xzadmin.pojo.User;
import com.xiaozhi.xzadmin.pojo.UserOnline;
import com.xiaozhi.xzadmin.service.sys.RoleService;
import com.xiaozhi.xzadmin.service.sys.UserOnlineService;
import com.xiaozhi.xzadmin.service.sys.UserService;
import com.xiaozhi.xzadmin.tools.AddressUtils;
import com.xiaozhi.xzadmin.tools.CookiesUtil;
import com.xiaozhi.xzadmin.tools.IpUtils;
import com.xiaozhi.xzadmin.tools.web.BaseController;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/admin/")
public class loginController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private UserOnlineService userOnlineService;
    String salt = new CommonUtil().getSalt();

    /***
     * 验证码是否开启
     * @return
     */
    public boolean isOpen = new CommonUtil().getCodeisOpen();
    /***
     * 登录页面
     * @return
     */
    @GetMapping({"/login","/"})
    public String getlogin(Model model){
        if (StpUtil.isLogin()){
            return "redirect:/admin/index";
        }
        model.addAttribute("isOpen",isOpen);
        return "login";
    }

    /***
     * 登录页面处理
     * @return
     */
    @AopLogger(title = "登录验证")
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult postlogin(HttpServletRequest request, @RequestBody User user, HttpServletResponse response){
        if (isOpen){
            String verCode = user.getVerCode();
            if ("".equals(verCode) || verCode.length()!=5){
                // 清除session中的验证码
                CaptchaUtil.clear(request);
                return error("验证码错误");
            }
            //验证码不正确
            if (!CaptchaUtil.ver(verCode, request)) {
                // 清除session中的验证码
                CaptchaUtil.clear(request);
                return error("验证码错误");
            }
        }
        List<User> users = userService.getUsernametopassword(user);
        if (users.size() != 0){
            if (users.get(0).getIs_off() == 1){
                return error("账号已被封禁,请联系管理员");
            }
            if (user.getRemember() == null){
                user.setRemember(false);
            }
            String rid =String.valueOf(roleService.getridByrid(users.get(0).getUserId()));
            StpUtil.login(users.get(0).getUserId());

            CookiesUtil.setCookie(response,"username",user.getUsername());
            CookiesUtil.setCookie(response,"rid", SaSecureUtil.md5BySalt(rid,salt));

//            设置在线信息
            UserOnline userOnline = new UserOnline();
            //token
            userOnline.setSessionId(StpUtil.getTokenValue());
            //用户名
            userOnline.setLoginName(user.getUsername());
            //ip
            userOnline.setIpaddr(IpUtils.getIpAddr(request));
            //地址
            userOnline.setLoginLocation(AddressUtils.getRealAddressByIP(IpUtils.getIpAddr(request)));

            String agent=request.getHeader("User-Agent");
            //解析agent字符串
            UserAgent userAgent = UserAgent.parseUserAgentString(agent);
            //获取浏览器对象
            Browser browser = userAgent.getBrowser();
            //获取操作系统对象
            OperatingSystem operatingSystem = userAgent.getOperatingSystem();

            userOnline.setBrowser(browser.getName());
            userOnline.setOs(operatingSystem.getName());

            userOnline.setStatus("on_line");
            userOnline.setStartTimestamp(new Date());
            userOnline.setLastAccessTime(new Date());
            userOnlineService.save(userOnline);
            return success("登录成功");
        }
        return error("密码错误");
    }
    /***
     * 注销
     * @return
     */
    @AopLogger(title = "登录退出")
    @RequestMapping("/logout")
    @ResponseBody
    public AjaxResult loginout() {
        UserOnline userOnline = new UserOnline();
        userOnline.setStatus("off_line");
        //token
        userOnline.setSessionId(StpUtil.getTokenValue());
        userOnline.setLastAccessTime(new Date());
        userOnlineService.update(userOnline);
        StpUtil.logout();
        return success("退出成功");
    }

}
